import store from '@/store'
import router from '@/router'
import axios from 'axios'
import { Message } from 'element-ui'

const service = axios.create({
  // 获取当前处于哪种开发模式
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 添加请求拦截器
service.interceptors.request.use(function(config) {
  const token = store.getters.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, function(error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
service.interceptors.response.use(function({ data }) {
  if (data.success) {
    Message.success(data.message)
  } else {
    Message.error(data.message)
    return Promise.reject(new Error(data.message))
  }
  return data
}, function(error) {
  console.dir(error)
  const { status, data } = error.response
  if (status === 401 || data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
    Message.error('登录超时，请重新登录')
  }
  return Promise.reject(error)
})
export default service
